Posts = new Mongo.Collection('posts');
Posts.allow({
    update: function (userId, post) {
        return ownsDocument(userId, post);
    },
    remove: function (userId, post) {
        return ownsDocument(userId, post);
    }
});
Posts.deny({
    update: function (userId, post, fieldNames) {
        console.log(fieldNames);
        return (_.without(fieldNames, 'url', 'title').length > 0);
    }
});
Posts.deny({
    update: function (userId, post, fieldNames, modifier) {
        console.log(fieldNames, modifier);
        var errors = validatePost(modifier.$set);
        return errors.title || errors.url;
    }
});
Meteor.methods({
    postInsert: function (postAttributes) {
        check(Meteor.userId(), String);
        check(postAttributes, {
            url: String,
            title: String
        });
        // if (Meteor.isServer) {
        //     postAttributes.title += "(server)";
        //     // wait for 5 seconds
        //     Meteor._sleepForMs(5000);
        // } else {
        //     postAttributes.title += "(client)";
        // }
        var errors = validatePost(postAttributes);
        if (errors.title || errors.url) {
            throw new Meteor.Error('invalid-post', "你必须为你的帖子填写标题和 URL");
        }
        var postWithSameLink = Posts.findOne({
            url: postAttributes.url
        });
        if (postWithSameLink) {
            return {
                postExists: true,
                _id: postWithSameLink._id
            }
        }
        var user = Meteor.user();
        var post = _.extend(postAttributes, {
            userId: user._id,
            author: user.username,
            submitted: new Date(),
            commentsCount: 0,
            upvoters: [],
            votes: 0
        });
        var postId = Posts.insert(post);
        return {
            _id: postId
        };
    },
    upvote:function(postId){
        check(this.userId,String);
        check(postId,String);
        // var post = Posts.findOne(postId);
        // if(!post){
        //     throw new Meteor.Error('invalid', 'Post not found');
        // }
        // if(_.include(post.upvoters,this.userId)){
        //     throw new Meteor.Error('invalid','您已经赞过了哦！',500);
        // }
        var result = Posts.update({
            _id:postId,
            upvoters:{$ne:this.userId}
        },{
            $addToSet:{upvoters:this.userId},
            $inc:{votes:1}
        });
        if(!result){
            throw new Meteor.Error('invalid','您不能点赞！',500);
        }
    }
});

validatePost = function (post) {
    var errors = {};
    if (!post.title) {
        errors.title = '请填写标题！';
    }
    if (!post.url) {
        errors.url = '请填写url！';
    }
    return errors;
}